﻿@model smp.ButterflyCakes.Models.FormModels.Order.ComponentSizeModel

<div class="container">
    <div class="container-fluid">
        @if (ViewBag.Error != null)
        {
            <div class="alert alert-block alert-error">
                <p>@ViewBag.Error</p>
            </div>
        }
        @Html.ValidationSummary(true)
    </div>
    
    <div class="form-actions hideWhenEditing">
        @if(Model.IsCarved)
        {
            <a href="/order/shapebuilder/@Model.ComponentId" class="btn btn-info" portiontype="true" style="color: white">Use Shape Builder</a><br />   
        }
        <strong>Requested Portions : @Model.TotalPortions</strong>
    </div>

    <div class="container hideWhenEditing">
        <div id="RemoveSizeError" class="alert alert-error hide">
            <button class="close" data-dismiss="alert" type="button">
                ×</button>
            <strong>Error</strong><p id="RemoveSizeErrorMessage">
            </p>
        </div>
        <table id="sizes" class="table table-bordered table-hover">
            <tr>
                <th>Size</th>
                <th>Portions</th>
                <th></th>
                <th></th>
            </tr>
            @if (Model.Sizes.Count == 0)
            {
                <tr class="nosizesrow">
                    <td colspan="4">
                        Please add a size
                    </td>
                </tr>
            }
            else
            {
                <tr class="nosizesrow hide">
                    <td colspan="4">
                        Please add a size
                    </td>
                </tr>
            }
            @foreach (var size in Model.Sizes)
            {
                <tr>
                    <td>
                        @size.DisplayName
                    </td>
                    <td>
                        @size.Portions
                    </td>
                    <td>
                        <button class="btn btn-info editSize" type="button"  SizeId="@size.SizeId" Size="@size.Size" Width="@size.Width" Shape="@size.ShapeInt" Portions="@size.Portions" CustomDetail="@size.CustomDetail">
                            Edit</button>
                    </td>
                    <td>
                        <button class="btn btn-danger removeSize" type="button" SizeId="@size.SizeId">
                            Remove</button>
                    </td>
                </tr>
            }
        </table>
    </div>
    
    <div class="form-actions hideWhenEditing">
        <button id="addASize" type="button" class="btn btn-info">
            Add a Shape
        </button>
    </div>

    <div id="SaveSizeSuccess" class="alert alert-success hide">
        <button class="close" data-dismiss="alert" type="button">
            ×</button>
        <strong>Success</strong>Size was added to this cake
    </div>

    <div id="AddSizeContainer" class="container hide">
        
        <input type="hidden" value="" name="SizeId" id="SizeId"/>
        
        <div id="SaveSizeError" class="alert alert-error hide">
            <button class="close" data-dismiss="alert" type="button">
                ×</button>
            <strong>Error</strong><p id="SaveSizeErrorMessage">
                                  </p>
        </div>
        
        <div class="control-group">
            <label class="control-label" for="Portions">
                How Many Portions</label>
            <div class="controls">
                <input class="intspinner" type="text" id="Portions" name="Portions" placeholder="Enter a title" value=""/>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="Quantity">
                Calculate Sizes For</label>
            <div class="controls">
                <div id="portionsSelectorType">
                    <a href="#" class="btn btn-info portionTypeSelector" portiontype="true" style="color: white">
                        Party Portions</a> <a href="#" class="btn btn-info portionTypeSelector" portiontype="false"
                                              style="color: white">Wedding Portions</a>
                </div>
                <div id="portionsSelectorContainer" class="hide" style="max-width: 50%; max-height: 250px; overflow-x: hidden; overflow-y: scroll; padding-bottom: 10px;">
                    
                </div>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="FlavourType">
                Shape
            </label>
            @MvcHtmlString.Create(Model.SelectShape.SetElementId("Shape").Html)
        </div>
        
        <div id="SizeGroup" class="control-group">
            <label id="SizeLabel" class="control-label" for="Size">
                Diameter (inches)</label>
            <div class="controls">
                <input class="intspinner calc" type="text" id="Size" name="Size" placeholder="Enter size" value="">
            </div>
        </div>
        
        <div id="WidthGroup" class="control-group hide">
            <label class="control-label" for="Width">
                Width (inches)</label>
            <div class="controls">
                <input class="intspinner calc" type="text" id="Width" name="Width" placeholder="Enter size" value="">
            </div>
        </div>
       
        
        @if (Model.IsCarved)
        {
            <div class="control-group">
                <label class="control-label" for="CustomShapeDetail">
                    Custom Shape Detail</label>
                <div class="controls">
                    <textarea class="summary" rows="5" id="CustomShapeDetail" name="CustomShapeDetail"
                              placeholder="Custom Shape Detail"></textarea>
                </div>
            </div>
        }

        <div id="porttionsestimatecontainer" class="hide">
            <p>
                Approximate portions :</p>
            <p>
                <strong id="fruitportions"></strong> wedding portions</p>
            <p>
                <strong id="spongeportions"></strong> party portions</p>
        </div>

        <div class="form-actions">
            <button id="SaveSize" type="submit" class="btn btn-success">
                Save Size</button>
            <button id="CancelSaveSize" type="submit" class="btn btn-warning">
                Cancel</button>
            <div id="addSpinner" class="loadingimg hide" style="height: 25px">
                <img src="@Url.Content("~/Content/images/ajax-loader.gif")" alt="Loading..."/>
            </div>
        </div>

    </div>

    <form class="form-horizontal" id="editform" url="/order/CompleteCakeSize">
        @Html.HiddenFor(x => x.ComponentId)
        @Html.HiddenFor(x => x.OrderId)
        @Html.HiddenFor(x => x.IsCarved)
    </form>

    <div class="form-actions hideWhenEditing">
        <button id="save" type="submit" class="btn btn-success">
            Next
        </button>
        <button id="cancel" type="submit" class="btn btn-danger hide">
            Cancel
        </button>
    </div>

</div>

<script type="text/javascript">

    var shape = $('#Shape');
    var size = $('#Size');
    var width = $('#Width');


    

    function CalculatePortions() {
        var element = $('#porttionsestimatecontainer');

        var shapeVal = shape.val();
        if (shapeVal == "Please select") {
            element.fadeOut(250);
            return;
        }

        var sizeVal = parseInt(size.val(), 10);
        if (sizeVal == 0) {
            element.fadeOut(250);
            return;
        }

        var surfaceArea;
        switch (shapeVal) {
            case "2":
                var widthVal = parseInt(width.val(), 10);
                if (widthVal == 0) {
                    element.fadeOut(250);
                    return;
                }
                surfaceArea = widthVal * sizeVal;
                break;
            case "1":
                surfaceArea = sizeVal * sizeVal;
                break;
            case "0":
                surfaceArea = 3.1416 * sizeVal;
                break;
            default:
                element.fadeOut(250);
                return;
        }

        $('#fruitportions').text(Math.floor(surfaceArea * 0.95));
        $('#spongeportions').text(Math.floor(surfaceArea / 2));

        element.fadeIn(500);
        Highlight(element);
    };

    function SetShape() {

        if (shape.val() == "2") {
            $('#SizeLabel').text('Length (inches)');
            $('#WidthGroup').slideDown(250);
            return;
        }

        $('#WidthGroup').slideUp(250);

        if (shape.val() == "1") {
            $('#SizeLabel').text('Size (inches)');
            return;
        }

        if (shape.val() == "0") {
            $('#SizeLabel').text('Diameter (inches)');
        }
    };

    function SelectPortions() {
        var portions = $('#Portions').val();
        if (portions == "0")
            return;
        var isPartyPortions = $(this).attr('portiontype');
        PostReturningHtml("/order/potentialsizes", { Portions: portions, IsPartyPortions: isPartyPortions, IsCarved: $('#IsCarved').val() }, $('#portionsSelectorContainer'), function () {
            $('.selectsize').click(function () {
                shape.val($(this).attr('cakeshape'));
                size.val($(this).attr('size'));
                width.val($(this).attr('width'));
                $('#portionsSelectorContainer').slideUp(500);
                $('#portionsSelectorContainer').empty();
                SetShape();
            });
            $('#portionselectcancel').click(function () {
                $('#portionsSelectorContainer').slideUp(500);
                $('#portionsSelectorContainer').empty();
            });
        });
    }

    function HandleFailedSave(error) {
        $('#SaveSizeErrorMessage').text(error);
        $('#SaveSizeError').slideDown(500);
        $('.hideWhenEditing').slideDown(250);
    }


    function HandleSuccessfulSave(id) {
        $('#SaveSizeSuccess').slideDown(500);
        $('.nosizesrow').slideUp(100);
        var display = '';
        if($('#IsCarved').val() == 'true') {
            display = 'Custom ';
        }
        if($('#Shape').val() == '0') {
            display = display + 'Round ' + $('#Size').val() + ' inches diameter';
        }
        if($('#Shape').val() == '1') {
            display = display + 'Square ' + $('#Size').val() + ' inches across';
        }
        if($('#Shape').val() == '2') {
            display = display + 'Rectangle ' + $('#Size').val() + ' inches by ' + $('#Width').val() + ' inches';
        }

        
        $('#sizes tr:last').after('<tr><td>' + display + '</td><td>' + $('#Portions').val() + '</td><td><button class="btn btn-info editSize" type="button"  SizeId="' + id + '" Size="' + $('#Size').val() + '" Width="' + $('#Width').val() + '" Shape="' + $('#Shape').val() + '" Portions="' + $('#Portions').val() + '" CustomDetail="' + $('#CustomShapeDetail').text() + '">Edit</button></td><td><button class="btn btn-danger removeSize" type="button" SizeId="' + id + '">Remove</button></td></tr>');
        $('#sizes tr:last').slideDown(250);
        Highlight($('#sizes tr:last'));
        if ($('.editing')[0]) {
            $('.editing').remove(); 
        }

        $('#AddSizeContainer').slideUp(250);
        $('.hideWhenEditing').slideDown(250);
        RegisterLoadEvents();
        setTimeout(function () {
            $('#SaveSizeSuccess').slideUp(500);
        }, 5000);
    }
    
    function AddSize() {
        $('#SaveSizeError').slideUp(100);
        $('#SaveSizeSuccess').slideUp(100);
        $('#addSpinner').fadeIn(100);
        var data = { SizeId: $('#SizeId').val(), ComponentId: $('#ComponentId').val(), Shape: $('#Shape').val(), Size: $('#Size').val(), Width: $('#Width').val(), Portions: $('#Portions').val(), CustomDetail: $('#CustomShapeDetail').text() };
        $.ajax({
            url: '/order/savesize',
            type: "POST",
            data: data,
            dataType: "json",
            success: function(result) {
                if (result.Success) {
                    HandleSuccessfulSave(result.Id);
                } else {
                    HandleFailedSave(result.ErrorMessage);
                }
            },
            fail: function() {
                HandleFailedSave('Unable to save the shape, please try again.');
            }
        });

        $('#addSpinner').fadeOut(100);
    }

    function HandleSuccessfulRemove(el) {
        $(el).parent().parent().slideUp(250);
        $(el).parent().parent().remove();
        if($('#sizes tr').length == 2) {
            $('.nosizesrow').slideDown(250);
        }
    }

    function HandleFailedRemove(error) {
        $('#RemoveSizeErrorMessage').text(error);
        $('#RemoveSizeError').slideDown(500);
    }

    function RemoveSize(el) {

        $('#removeSpinner').fadeIn(100);
        $('#RemoveFlavourError').slideUp(100);
        var data = { ComponentId: $('#ComponentId').val(), SizeId: $(el).attr('SizeId') };

        $.ajax({
            url: '/order/removesize',
            type: "POST",
            data: data,
            dataType: "json",
            success: function (result) {
                if (result.Success) {
                    HandleSuccessfulRemove(el);
                } else {
                    HandleFailedRemove(result.ErrorMessage);
                }
            },
            fail: function () {
                HandleFailedRemove('Unable to save the flavour, please try again.');
            }
        });
        $('#removeSpinner').fadeOut(100);
    }

    function EditSize(el) {
        $(el).parent().parent().addClass('editing');
        $('#SizeId').val($(el).attr('SizeId'));
        $('#Shape option[value=' + $(el).attr('Shape') + ']').attr('selected', 'selected');
        $('#Size').val($(el).attr('Size'));
        $('#Width').val($(el).attr('Width'));
        $('#Portions').val($(el).attr('Portions'));
        $('#CustomShapeDetail').val($(el).attr('CustomDetail'));
        $('.hideWhenEditing').slideUp(250, function () {
            $('#AddSizeContainer').slideDown(250); 
        });
    }

    function RegisterLoadEvents() {
        $('.removeSize').click(function (e) {
            e.preventDefault();
            RemoveSize(this);
        });

        $('.editSize').click(function(e) {
            e.preventDefault();
            EditSize(this);
        });
    }

    $(document).ready(function () {

        shape.change(function () {
            setTimeout(function () {
                SetShape();
            }, 500);
        });

        $('.calc').change(function () {
            setTimeout(function () {
                CalculatePortions();
            }, 500);
        });

        $('.portionTypeSelector').click(function () {
            SelectPortions();
        });

        $('#addASize').click(function (e) {
            e.preventDefault();
            $('.hideWhenEditing').slideUp(250);
            $('#SizeId').val('');
            $('#Shape').val('');
            $('#Size').val('');
            $('#Width').val('');
            $('#Portions').val('');
            $('#CustomShapeDetail').val('');
            $('#AddSizeContainer').slideDown(250);
        });

        $('#CancelSaveSize').click(function (e) {
            e.preventDefault();
            $('#AddSizeContainer').slideUp(250);
            $('.hideWhenEditing').slideDown(250);
            $('.editing').removeClass('editing');
        });

        $('#SaveSize').click(function (e) {
            e.preventDefault();
            AddSize();
        });

        RegisterLoadEvents();
    });
</script>